﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using Scoreboard.Model;
using Scoreboard.Data;
using Scoreboard.Basement;
using Microsoft.Practices.Composite.Events;
using Scoreboard.Basement.Events;

namespace Scoreboard.Model.Services
{
	public partial class ScoreboardDomainContext
	{
		private User _currentUser;
		private bool _isCurrentUserLoading;

		public User CurrentUser
		{
			get
			{
				if (_currentUser == null)
				{
					LoadCurrentUser();
				}
				return _currentUser;
			}
		}

		partial void OnCreated()
		{
			var eventAggregator = ServiceLocator.Get<IEventAggregator>();
			var userAuthenticatedEvent = eventAggregator.GetEvent<UserAuthenticatedEvent>();

			userAuthenticatedEvent.Subscribe(UserAuthenticatedHandler);

			LoadCurrentUser();

		}

		public void UserAuthenticatedHandler(bool isAuthenticated)
		{
			LoadCurrentUser();
		}

		private void LoadCurrentUser()
		{
			if (_isCurrentUserLoading)
			{
				return;
			}

			if (WebContext.Current.User.IsRegistered)
			{
				_isCurrentUserLoading = true;
				Load(GetUsersQuery().Where(u => u.Login == WebContext.Current.User.Name),
												LoadCurrentUserCallback,
												null);				
			}
		}

		private void LoadCurrentUserCallback(LoadOperation<User> operation)
		{
			_currentUser = operation.Entities.Single();
			_isCurrentUserLoading = false;
		}
	}
}
